/*Copyright 2012 Google Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
#limitations under the License.*/

/* Settings & defaults

	BossClass

	rotAngle			undefined	faceAngleRadians
	dir					undefined	dir 			vec2 initial direction of movement
	!!dirNormalize		undefined 	dirNormalize	normalize dir vector so speed is always speed
	lifetime			0			lifetimeInSeconds
	_dmgAmt				0			damage			amount of damage dealt onTouch
	health				10 			health
	_speed				0 			speed
	_animFrameName		undefined	animFrameName	
	_impactFrameName	undefined	impactFrameName
	_impactSound		undefined	impactSound

						
*/		

BossClass = EnemyClass.extend({

	collidesWith : ['player', 'pprojectile', 'mapobject'],
	categories : ['enemy'],
	
	init: function (inputx, inputy, settings) 
	{
		
		this.parent(inputx, inputy, settings);
		if (settings) 
		{

		};
		
	},
	/*
	AI: function ()
	{
		// specific code here
		
		this.parent();
	},
	
    update: function () 
	{	
		this.parent();
	},
  
	onTouch: function (otherBody, point, impulse) 
	{
		this.parent(otherBody, point, impulse);
		//this.markForDeath = true;
	},

	*/

	kill: function() {
		this.parent();
		// Z TODO: code to signal death of a boss enemy: pick up by campaign and game stats
	},
	
	on_stats: function(msg) {
		this.parent(msg);
		// TO DO : a different destroy effect for each class
	},
	//--------------------------------------

}); // generic class BossClass

MotherBeeBossClass = BossClass.extend({

	collidesWith : ['player', 'pprojectile', 'mapobject'],
	categories : ['enemy'],
	
	init: function (inputx, inputy, settings) 
	{
		this.parent(inputx, inputy, settings);
		this.lifetime = 200;
		this.drones = {
			list : [],
			spawnTimer : 15, // spawn in 15 seconds from now
			spawnInterval : 20, // spawn every 50 seconds after that
			spawnDelay : 0.5, // available drone slots get spawned every 0.5 secs
			max : 6,
			angle : 0, // circle angle of first drone
			radius : 100,
			chargeTimer : 20,
			chargeInterval : 12, // charge every 12 seconds
			chargeLength : 4 // drones attack for 5 seconds then return
		};
		
		this.element = {
			body : { 
				id : this.id+"_body",
				vulnerable : true,
				health : 10000,
				isDead : true,
				offset : {x: 0, y: 0}
				}, 
			head : {
				id : this.id+"_head",
				vulnerable : true,
				health : 5000,
				offset : {x : -64, y : 0}
			},
			spawnBay : {
				id : this.id+"_spawnBay",
				vulnerable : true,
				health : 2000,
				offset: {x : +16, y : +32}
			},
			freezeTurret : {
				id : this.id+"_freezeTurret",
				vulnerable : true,
				health : 1000,
				offset: {x : -16, y : -32},
				weapon : {}
			}
		};
		// for spawning
		this._spawnDir = new Vec2(-.5,0);
		this._spawnDirVariation = 0;
		this._spawnAcceleration = {x:0, y: 0};
		this._spawnOffset = {x:16, y: 16};

		var entityDef = {
		  id: "MotherBeeBoss"+this.id,
		  x: this.pos.x,
		  y: this.pos.y,
		  halfHeight: 32,
		  halfWidth: 64,
		  damping: 10,
		  angle: 0,
		  categories: this.categories, 
		  collidesWith: this.collidesWith,
		  userData: {
			"id": this.element.body.id,
			"ent": this,
			"element" : this.element.body
		  },
		  moreShapes: [{
			halfWidth : 16, halfHeight : 16,
			offset : this.element.head.offset,
			userData : {
				"id": this.element.head.id,
				"element": this.element.head
			}
		  },{
			halfWidth : 16, halfHeight : 16,
			offset : this.element.spawnBay.offset,
			userData : {
				"id": this.element.spawnBay.id,
				"element": this.element.spawnBay
			}
		  },{
			halfWidth : 8, halfHeight : 8,
			offset : this.element.freezeTurret.offset,
			userData : {
				"id": this.element.freezeTurret.id,
				"element": this.element.freezeTurret
			}
		  }]
		};
		this.physBody = gPhysicsEngine.addBody(entityDef);
		this.dir.x = .2;
		this.physBody.SetLinearVelocity(new Vec2(this.dir.x * this._speed, this.dir.y * this._speed));
		this.calcHealth();
		this.maxHealth = this.health;
	
		if(IS_CLIENT)
		{
			this.zIndex = 20;
			this._spriteAnim = new SpriteSheetAnimClass();
			this._spriteAnim.loadSheet('sotee_sprites',"./img/sotee_sprites.png");
			var sprites = getSpriteNamesSimilarTo("motherbee");
			for(var i =0; i < sprites.length; i++)
				this._spriteAnim.pushFrame(sprites[i]);
		}
	},

	AI: function ()
	{
		// specific code here

		if (this.drones.spawnTimer<0) {
			this.drones.spawnTimer += this.drones.spawnInterval;
			if (!this.element.spawnBay.isDead) this.spawnDrones();
		};
		if (this.drones.chargeTimer<0) {
			this.drones.chargeTimer += this.drones.chargeInterval;
			this.chargeDrones(true);
		};
		this.circleDrones();
		this.parent();
	},
	
    update: function () 
	{	
		this.drones.spawnTimer -= .05;
		// Z: check for destroyed elements to set isDead
		for (var i=0;i<this.drones.list.length;i++) {
			if (!this.drones.list[i] || this.drones.list[i]._killed) this.drones.list.splice(i,1);
		}
		this.calcHealth();
		this.parent();
	},

	calcHealth: function () 
	{
		this.health = 0;
		for (var e in this.element) {
			if (this.element[e].health) {
				if (this.element[e].health<=0) { 
					this.element[e].isDead=true 
				} else { 
					this.health+=this.element[e].health
				}
			}
		}
	},

	spawnDrones: function () {
		if (this.drones.list.length<this.drones.max) {
			this.drones.list.push(this.spawn("FloatMine"));
			setInterval(this.spawnDrones(), this.drones.spawnDelay*1000);
		}
	},

	chargeDrones: function(arm) {
		for (var i=0;i<this.drones.list.length;i++) {
			this.drones.list[i].armed = arm;
			this.drones.list[i].moveTo = {x: this.pos.x, y: this.pos.y};
		};
		if (arm) setInterval(this.chargeDrones(false),this.drones.chargeLength*1000);
	},

	circleDrones: function() {
		var r = 2*Math.PI/this.drones.list.length; // radial per drone
		this.drones.angle = this.drones.angle + .1; 
		if (this.drones.angle>2*Math.PI) this.drones.angle = 0;
		for (var i=0;i<this.drones.list.length;i++) {
			if (this.drones.list[i].armed) continue;
			this.drones.list[i].moveTo.x = this.pos.x + Math.sin(this.drones.angle+r*i)*this.drones.radius;
			this.drones.list[i].moveTo.y = this.pos.y + Math.cos(this.drones.angle+r*i)*this.drones.radius;
			this.drones.list[i].centerAt({x:dPX,y:dPY}); // ok, quick fix, the're gonna jump around.
		}
	},

	draw: function (fractionOfNextPhysicsUpdate) { // Z: CLIENT code only called by CLIENT
		var gMap = gGameEngine.gMap;
		var ctx = gRenderEngine.context;
	
		var pPos = this.pos;
		if (this.physBody) pPos = this.physBody.GetPosition();
	
		var interpolatedPosition = {x:pPos.x, y:pPos.y};
	
		if(this.physBody) {
		  var velocity = this.physBody.GetLinearVelocity();
		  interpolatedPosition.x += (velocity.x * Constants.PHYSICS_LOOP_HZ) * fractionOfNextPhysicsUpdate;
		  interpolatedPosition.y += (velocity.y * Constants.PHYSICS_LOOP_HZ) * fractionOfNextPhysicsUpdate;
		}

		//this._spriteAnim.draw(interpolatedPosition.x,interpolatedPosition.y,{rotRadians:this.rotAngle});	
		ctx.strokeStyle = "green";
		ctx.lineWidth = 2;
	    var dPX = gRenderEngine.getScreenPosition(interpolatedPosition).x;
	    var dPY = gRenderEngine.getScreenPosition(interpolatedPosition).y;
	    ctx.strokeRect(dPX - 64, dPY - 32, 128, 64); //body
	    ctx.strokeStyle=(this.element.spawnBay.isDead)?"green":"orange";
	    gRenderEngine.drawString(this.element.spawnBay.health, 'roboto', dPX - 64, dPY - 32, 8, {color:"green"});
	    ctx.strokeRect(dPX + 16 - 16, dPY + 32 - 16, 32, 32); //spawnbay
	    ctx.strokeStyle=(this.element.head.isDead)?"green":"orange";
	    gRenderEngine.drawString(this.element.head.health, 'roboto', dPX - 64, dPY - 16, 8, {color:"green"});
	    ctx.strokeRect(dPX - 64 - 16, dPY - 16, 32, 32); //head
	    ctx.strokeStyle=(this.element.freezeTurret.isDead)?"green":"orange";
	    ctx.strokeRect(dPX - 16 - 8, dPY - 32 - 8, 16, 16); //turret4
		gRenderEngine.drawString(this.element.freezeTurret.health, 'roboto', dPX - 16, dPY - 32, 8, {color:"green"});
		gRenderEngine.drawString(this.element.body.health, 'roboto', dPX - 64, dPY + 32, 8, {color:"green"});

		ctx.fillStyle = "red";
		ctx.fillRect(dPX - 68, dPY - 48, (120 * this.health / this.maxHealth), 6);
		ctx.strokeStyle = "grey";
		ctx.lineWidth = 2;
		ctx.strokeRect(dPX - 68, dPY - 48, 120, 6);
  	},

	onTouch: function (otherFixture, point, impulse) 
	{
		this.parent(otherFixture, point, impulse);
		//this.markForDeath = true;
	},

	kill: function() {
		this.parent();
	},
	
	on_stats: function(msg) {
		if (!IS_CLIENT) return; // make this client code only
		for (var e in this.element) { // check if any of the elements died
			if(e.health<=0 && !e.isDead)
			{
			  //spawn element death explosion!

			  var efct = gGameEngine.spawnEntity("InstancedEffect", this.pos.x+e.offset.x, this.pos.y+e.offset.y, null);
			  efct.onInit({x:this.pos.x+e.offset.x,y:this.pos.y+e.offset.y},
					  {	playOnce:true, 
						  similarName: this.deathEffect || "explosionC", 
						  uriToSound:"./sound/explosionA.ogg"
					  });
			}
		}
		this.parent(msg); //this will check for entitydeath
		// TO DO : a different destroy effect for each class
	},

	takeDamage: function(amount, fixture) 
	{
	  var u = fixture.GetUserData();
	  if (u==null) u = fixture.GetBody().GetUserData(); // we hit the main element, get the body userdata
	  var e = u.element;
	  if (e.vulnerable) {
	  	e.health -= amount;
	  	if (e.health<0) {
	  		e.health = 0;
	  		e.destroyed = true;
	  	}
	  }
	}
	//--------------------------------------

});

Factory.nameClassMap['MotherBeeBoss'] = MotherBeeBossClass;

